// pages/shopcart/shopcart.js
const shopcartService = require('../../../../api/shopcartService.js')
const productService = require('../../../../api/productService.js')
const secKillService = require('../../../../api/seckillService.js')
const storeService = require('../../../../api/storeService.js')
const newmbrActivityService = require('../../../../api/newmbrActivityService.js')
const util = require('../../../../utils/utils.js')

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabbar: {},
    checkedAll: false,
    allPrice: "0.00",
    discount: 0.00,
    category: [],
    goodsList: [],
    storeName: '人民广场店',
    tabSelected: 0,
    distributionStoreId: '',
    distributionStoreName: '',
    goodsNum: {
      storeNum: 0,
      distributionNum: 0
    },
    hasUserInfo: false,
    modal: false,
    goodsInfo: null,
    show: {
      middle: false,
      top: false,
      bottom: false,
      right: false,
      right2: false
    },
    overlayStyle: 'background: rgba(255, 255, 255, 0.9)',
    showTabbar: true,
    phone: false
  },

  // 前往首页
  toHome: function () {
    wx.switchTab({
      url: '../../index/index/index'
    })
  },
  // 类目点击事件
  clickCategory: function (e) {
    this.setData({
      tabSelected: e.currentTarget.dataset.idx,
    })
    const distributionStoreName = this.data.distributionStoreName
    if (e.currentTarget.dataset.idx == 0) {
      if (app.globalData.storeInfo) {
        this.setData({
          storeName: app.globalData.storeInfo.name
        })
      }
    } else {
      if (distributionStoreName) {
        this.setData({
          storeName: distributionStoreName
        })
      }
    }
    this.queryShopcart()
    console.log(this.data.tabSelected)
  },
  // 购物车同步操作
  handleSync: function (postData) {
    const that = this
    let tempList = []
    console.log(postData)
    let storeId = postData.storeId
    // let tempData = postData.lists[0]
    if (postData.newmbrActivityId) {
      if (postData.count < 0) {
        shopCartSync(postData);
      } else {
        wx.showToast({
          title: "新用户专享只能购买一件哦~",
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      shopCartSync(postData);
    }
    if (postData.grabActivityId) {

    }

    function shopCartSync(postData) {
      shopcartService.update(postData).then(res => {
        util.setHideLoading(true);
        console.log(postData)
        // this.queryShopcart();
        const goodsId = postData.shoppingItemId
        const goodsList = that.data.goodsList
        goodsList.forEach(item => {
          if (item.id === goodsId) {
            let num = postData.count
            let tempData = {
              ...item,
              productNum: num
            }
            tempList.push(tempData)
          } else {
            tempList.push(item)
          }
        })
        return storeId;
      }).then(storeId => {
        shopcartService.getCatering(storeId).then(res => {
          console.log(res)
          res.items.forEach((ele, index) => {
            if (ele.id === tempList[index].id) {
              tempList[index].discount = ele.discount
            }
          });
          that.setData({
            goodsList: tempList
          })
          return storeId;
        }).then(storeId => {
          that.queryInverntory(storeId)
        }).catch(err => {
          if (err.message != 'Access Token没有设置') {
            console.log(err.message)
          }
          that.setData({
            allPrice: '0.00',
          })
        })
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },

  // 数量价格计算
  handlePriceCalc: function () {
    let tempPrice = 0;
    let tempDiscount = 0;
    let tempList = []
    let storeId = ''
    if (this.data.tabSelected == 0) {
      if (app.globalData.storeInfo) {
        storeId = app.globalData.storeInfo.id
      }
    } else {
      storeId = that.data.distributionStoreId
    }
    this.data.goodsList.forEach(item => {
      if (item.checked) {
        tempPrice += item.sellPrice * item.productNum
        let tempItem = {
          productId: item.productId,
          productNum: item.productNum,
          sharingPersonId: ''
        }
        tempList.push(tempItem)
      }
    })
    if (tempList.length > 0) {
      let postData = {
        products: tempList,
        storeId: storeId
      }
      this.calcDiscount(postData, tempPrice)
    } else {
      this.setData({
        allPrice: tempPrice.toFixed(2),
        discount: tempDiscount.toFixed(2)
      })
    }
  },

  // 数量减事件
  handleReduce: function (e) {
    const that = this
    let tempData = this.data.goodsList;
    let tempLists = [];
    let productNum = 0;
    tempData.forEach(item => {
      if (item.id === e.currentTarget.dataset.id) {
        if (item.grabActivityId) {
          tempLists.push({
            count: item.productNum - 1,
            shoppingItemId: item.id,
            grabActivityId: item.grabActivityId
          })
        } else {
          tempLists.push({
            count: item.productNum - 1,
            shoppingItemId: item.id,
          })
        }
        productNum = item.productNum
      }
    })
    if (productNum > 1) {
      let tabSelected = this.data.tabSelected
      let storeId = ''
      if (tabSelected == 0) {
        storeId = app.globalData.storeInfo.id
      } else {
        storeId = this.data.distributionStoreId
      }
      let postData = {
        storeId: storeId,
        ...tempLists[0]
      }
      this.handleSync(postData)
    } else {
      wx.showToast({
        title: '该商品不能再减少了哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 数量加事件
  handleAdd: function (e) {
    let tempData = this.data.goodsList;
    let tempLists = [];
    const limitNum = 999
    tempData.forEach(item => {
      if (item.id === e.currentTarget.dataset.id) {
        console.log(item)
        if (item.productNum < limitNum) {
          console.log("12")
          if (item.productNum < item.balance) {
            if (item.secKillInfo) {
              if (item.productNum >= item.secKillInfo.limitCount) {
                wx.showToast({
                  title: '亲，' + item.name + '只可以秒杀' + item.secKillInfo.limitCount + '个，不可以贪心哦~',
                  icon: 'none',
                  duration: 2000
                })
              } else {
                tempLists.push({
                  count: item.productNum + 1,
                  shoppingItemId: item.id,
                })
              }
            } else {
              console.log("??????")
              if (item.orderCount) {
                if (item.productNum >= item.orderCount) {
                  wx.showToast({
                    title: '亲，' + item.name + '每单限购' + item.orderCount + '个哦~',
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  let tempData = {
                    count: item.productNum + 1,
                    shoppingItemId: item.id,
                  }
                  if (item.newmbrActivityId) {
                    tempData = {
                      ...tempData,
                      newmbrActivityId: item.newmbrActivityId
                    }
                  }
                  if (item.grabActivityId) {
                    tempData = {
                      ...tempData,
                      grabActivityId: item.grabActivityId
                    }
                  }
                  tempLists.push(tempData)
                }
              } else {
                let tempData = {
                  count: item.productNum + 1,
                  shoppingItemId: item.id,
                }
                if (item.newmbrActivityId) {
                  tempData = {
                    ...tempData,
                    newmbrActivityId: item.newmbrActivityId
                  }
                }
                if (item.grabActivityId) {
                  tempData = {
                    ...tempData,
                    grabActivityId: item.grabActivityId
                  }
                }
                tempLists.push(tempData)
              }
            }
          } else {
            wx.showToast({
              title: '我们只有这么多了~',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          wx.showToast({
            title: '我们只有这么多了~',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
    if (tempLists.length > 0) {
      let storeId = ''
      let tabSelected = this.data.tabSelected
      if (tabSelected == 0) {
        storeId = app.globalData.storeInfo.id
      } else {
        storeId = this.data.distributionStoreId
      }
      let postData = {
        storeId: storeId,
        ...tempLists[0]
      }
      this.handleSync(postData)
    }
  },
  // 输入数量
  handleNumber: function (e) {
    const that = this
    this.setData({
      modal: true
    })
    let tempData = this.data.goodsList;
    tempData.forEach(item => {
      if (item.id === e.currentTarget.dataset.id) {
        console.log(item)
        that.setData({
          goodsInfo: {
            ...item,
            focus: true
          }
        })
      }
    })
  },
  handleProductNumAdd: function () {
    let goodsInfo = this.data.goodsInfo
    let num = goodsInfo.productNum
    const limitNum = 999
    if (num < limitNum) {
      if (num < goodsInfo.balance) {
        if (goodsInfo.secKillInfo) {
          if (num >= goodsInfo.secKillInfo.limitCount) {
            wx.showToast({
              title: '亲，' + goodsInfo.name + '只可以秒杀' + goodsInfo.secKillInfo.limitCount + '个，不可以贪心哦~',
              icon: 'none',
              duration: 2000
            })
          } else {
            num++
            this.setData({
              goodsInfo: {
                ...goodsInfo,
                productNum: num
              },
            })
          }
        } else {
          if (goodsInfo.orderCount) {
            if (num >= goodsInfo.orderCount) {
              wx.showToast({
                title: '亲，' + goodsInfo.name + '每单限购' + goodsInfo.orderCount + '个哦~',
                icon: 'none',
                duration: 2000
              })
            } else {
              num++
              this.setData({
                goodsInfo: {
                  ...goodsInfo,
                  productNum: num
                },
              })
            }
          } else {
            num++
            this.setData({
              goodsInfo: {
                ...goodsInfo,
                productNum: num
              },
            })
          }
        }
      } else {
        wx.showToast({
          title: '我们只有这么多了~',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      wx.showToast({
        title: '已经达到最大了哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  handleProductNumReduce: function () {
    let goodsInfo = this.data.goodsInfo
    let num = goodsInfo.productNum
    if (num > 0) {
      num--
      console.log(num)
      this.setData({
        goodsInfo: {
          ...goodsInfo,
          productNum: num,
        },
      })
    } else {
      wx.showToast({
        title: '不能再小了哦~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 取消
  onCancel: function (e) {
    const that = this
    let tempData = this.data.goodsList;
    tempData.forEach(item => {
      if (item.id === e.currentTarget.dataset.id) {
        that.setData({
          goodsInfo: item,
          modal: false
        })
      }
    })
  },
  // 确认
  onConfirm: function (e) {
    const that = this
    let tempData = this.data.goodsList;
    let oldGoodsInfo = null
    let nowGoodsInfo = this.data.goodsInfo
    let tempLists = []
    tempData.forEach(item => {
      if (item.id === e.currentTarget.dataset.id) {
        oldGoodsInfo = item
      }
    })
    const num = nowGoodsInfo.productNum
    let tempGoodsData = {
      count: num,
      shoppingItemId: nowGoodsInfo.id
    }
    if (nowGoodsInfo.newmbrActivityId) {
      tempGoodsData = {
        ...tempGoodsData,
        newmbrActivityId: nowGoodsInfo.newmbrActivityId
      }
    }
    if (nowGoodsInfo.grabActivityId) {
      tempGoodsData = {
        ...tempGoodsData,
        grabActivityId: nowGoodsInfo.grabActivityId
      }
    }
    tempLists.push(tempGoodsData)
    if (tempLists.length > 0) {
      let storeId = ''
      let tabSelected = this.data.tabSelected
      if (tabSelected == 0) {
        storeId = app.globalData.storeInfo.id
      } else {
        storeId = this.data.distributionStoreId
      }
      let postData = {
        storeId: storeId,
        ...tempGoodsData
      }
      console.log(postData)
      this.handleSync(postData)
    }
    this.setData({
      modal: false
    })
  },
  bindProductNumInput: function (e) {
    let goodsInfo = this.data.goodsInfo
    const productNum = goodsInfo.productNum
    const limitNum = 999
    if (e.detail.value <= limitNum && e.detail.value > 0) {
      if (e.detail.value <= goodsInfo.balance) {
        if (goodsInfo.secKillInfo) {
          if (e.detail.value >= goodsInfo.secKillInfo.limitCount) {
            wx.showToast({
              title: '亲，' + goodsInfo.name + '只可以秒杀' + goodsInfo.secKillInfo.limitCount + '个，不可以贪心哦~',
              icon: 'none',
              duration: 2000
            })
            this.setData({
              goodsInfo: {
                ...goodsInfo,
                productNum: goodsInfo.secKillInfo.limitCount
              }
            })
          } else {
            this.setData({
              goodsInfo: {
                ...goodsInfo,
                productNum: e.detail.value
              }
            })
          }
        } else {
          if (goodsInfo.orderCount) {
            if (e.detail.value >= goodsInfo.orderCount) {
              wx.showToast({
                title: '亲，' + goodsInfo.name + '每单限购' + goodsInfo.orderCount + '个哦~',
                icon: 'none',
                duration: 2000
              })
              this.setData({
                goodsInfo: {
                  ...goodsInfo,
                  productNum: goodsInfo.orderCount
                }
              })
            } else {
              this.setData({
                goodsInfo: {
                  ...goodsInfo,
                  productNum: e.detail.value
                }
              })
            }
          } else {
            this.setData({
              goodsInfo: {
                ...goodsInfo,
                productNum: e.detail.value
              }
            })
          }
        }
      } else {
        this.setData({
          goodsInfo: {
            ...goodsInfo,
            productNum: goodsInfo.balance
          }
        })
        wx.showToast({
          title: '我们只有这么多了~',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      if (e.detail.value > 0) {
        this.setData({
          goodsInfo: {
            ...goodsInfo,
            productNum: limitNum
          }
        })
        wx.showToast({
          title: '已经达到最大限购数量了哦~',
          icon: 'none',
          duration: 2000
        })
      } else {
        this.setData({
          goodsInfo: {
            ...goodsInfo,
            productNum: 1
          }
        })
        wx.showToast({
          title: '该商品数量不能再小了哦~',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },

  clickBlank: function () {
    this.setData({
      modal: false
    })
  },
  clickBody: function () {

  },
  // checkbox监听事件
  checkboxChange: function (e) {
    if (e.detail.value.length === this.data.goodsList.length) {
      this.setData({
        checkedAll: true
      })
    } else {
      this.setData({
        checkedAll: false
      })
    }
    let tempData = this.data.goodsList;
    tempData.forEach(ele => {
      ele.checked = false;
    })
    e.detail.value.forEach(item => {
      tempData.forEach(ele => {
        if (item === ele.id) {
          ele.checked = true;
        }
      })
    })
    this.setData({
      goodsList: tempData
    })
    this.handlePriceCalc()
  },
  // 全选点击事件
  checkboxAllChange: function (e) {
    let tempData = this.data.goodsList;
    let tempList = []
    let storeId = ''
    if (this.data.tabSelected == 0) {
      if (app.globalData.storeInfo) {
        storeId = app.globalData.storeInfo.id
      }
    } else {
      storeId = that.data.distributionStoreId
    }
    if (e.detail.value.length === 0) {
      tempData.forEach((item, index) => {
        item.checked = false;
      })
      this.setData({
        goodsList: tempData
      })
    } else {
      tempData.forEach((item, index) => {
        if (item.status === 'DELETED' || item.balance === 0) {
          item.checked = false;
        } else {
          item.checked = true;
        }
      })
      this.setData({
        goodsList: tempData
      })
    }
    this.handlePriceCalc()
  },
  // 根据商品计算优惠金额
  calcDiscount: function (postData, allPrice) {
    const that = this
    console.log(allPrice)
    let tempAllPrice = allPrice
    shopcartService.calcDiscount(postData).then(res => {
      console.log(res)
      if (res) {
        tempAllPrice = (parseFloat(allPrice - res.discount)).toFixed(2)
        that.setData({
          allPrice: tempAllPrice,
          discount: res.discount
        })
      } else {
        that.setData({
          allPrice: tempAllPrice.toFixed(2),
          'discount': 0
        })
      }
    }).catch(e => {
      that.setData({
        allPrice: tempAllPrice.toFixed(2),
      })
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 购物车查询
  queryShopcart: function () {
    const that = this
    let tabSelected = that.data.tabSelected
    const oldGoodsList = that.data.goodsList
    const loginStatus = that.checkAuth()
    console.log("123")

    function getShopCartData(storeId) {
      var tempItems = [];
      if (storeId !== '' && loginStatus) {
        shopcartService.getCatering(storeId).then(res => {
          if (!util.isHideLoading()) {
            util.setHideLoading(true)
          }
          console.log(res)
          let checkedCount = 0
          res.items.forEach((ele, index) => {
            let produtlabel = []
            let promotions = []
            if (ele.labels && ele.labels.length > 0) {
              ele.labels.forEach(item => {
                if (item.type === 'GOODSLABEL') {
                  produtlabel.push(item)
                } else if (item.type === 'PROMOTIONLABEL') {
                  promotions.push(item)
                }
              })
            }
            ele = {
              ...ele,
              produtlabel: produtlabel,
              promotions: promotions,
            }
            if (ele.status === 'DELETED') {
              tempItems.push({
                ...ele,
                checked: false
              })
            } else {
              tempItems.push({
                ...ele,
                checked: false
              })
            }
            if (ele.sellPrice == null && ele.originalPrice !== null) {
              tempItems[index].sellPrice = ele.originalPrice
            }
          });
          if (oldGoodsList.length > 0 && tempItems.length > 0 && oldGoodsList.length === tempItems.length) {
            oldGoodsList.forEach((item, index) => {
              if (item.productId === tempItems[index].productId) {
                tempItems[index] = {
                  ...tempItems[index],
                  checked: item.checked
                }
                if (item.checked) {
                  checkedCount++
                }
              }
            })
          }
          console.log(checkedCount)
          if (checkedCount !== 0 && checkedCount === tempItems.length) {
            that.setData({
              checkedAll: true,
              //allPrice: res.allPrice,
              goodsList: tempItems
            })
          } else {
            that.setData({
              checkedAll: false,
              //allPrice: res.allPrice,
              goodsList: tempItems
            })
          }
          that.queryInverntory(storeId)
        }).catch(err => {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
          that.setData({
            checkedAll: false,
            allPrice: '0.00',
            goodsList: tempItems
          })
        })
      } else {
        that.setData({
          goodsList: []
        })
      }
    }
    if (tabSelected == 0) {
      if (app.globalData.storeInfo) {
        getShopCartData(app.globalData.storeInfo.id)
      } else {
        getShopCartData()
      }
    } else {
      getShopCartData(that.data.distributionStoreId)
    }
  },
  // 查询门店购物车商品数量
  queryAllShopcart: function (storeId) {
    let number = shopcartService.getCatering(storeId).then(res => {
      let num = res.items.length
      return num
    }).catch(err => {
      util.handleLoginStatus(err)
    })
    return number
  },
  // 查询购物车商品数量
  queryShopCartNum: function () {
    const that = this
    let storeNum = 0
    let distributionNum = 0
    if (app.globalData.storeInfo) {
      storeNum = this.queryAllShopcart(app.globalData.storeInfo.id)
    }
    console.log(that.data.distributionStoreId)
    if (that.data.distributionStoreId) {
      distributionNum = this.queryAllShopcart(that.data.distributionStoreId)
    }
    Promise.all([storeNum, distributionNum]).then((res) => {
      that.setData({
        goodsNum: {
          storeNum: res[0] ? res[0] : 0,
          distributionNum: res[1] ? res[1] : 0
        }
      })
    })
  },
  // 查询库存
  queryInverntory: function (storeId) {
    const that = this
    let tempGoodsList = [];
    let tempList = this.data.goodsList
    tempList.forEach(item => {
      let productId = item.productId
      let tempItems = productService.getDetails(storeId, productId).then(res => {
        let balance = ''
        if (res) {
          balance = res.balance
        } else {
          balance = 0
        }
        let specifications = null
        let produtlabel = []
        let promotions = []
        if (res.productProperties && res.productProperties.length > 0) {
          for (let i = 0; i < res.productProperties.length; i++) {
            const ele = res.productProperties[i];
            if (ele.propertyName === '规格') {
              specifications = ele.propertyValue
              break
            }
          }
        }
        if (res.labels && res.labels.length > 0) {
          res.labels.forEach(item => {
            if (item.type === 'GOODSLABEL') {
              produtlabel.push(item)
            } else if (item.type === 'PROMOTIONLABEL') {
              promotions.push(item)
            }
          })
        }
        let tempItems = {
          ...item,
          balance: balance,
          checked: balance === 0 ? false : item.checked,
          specifications: specifications ? specifications : '',
          produtlabel: produtlabel,
          promotions: promotions,
        }
        return tempItems
      });
      tempGoodsList.push(tempItems)
    })
    Promise.all(tempGoodsList).then((res) => {
      console.log("检查库存")
      that.querySecKillGoods(storeId, res)
      // that.setData({
      //   goodsList: res
      // })
    })
  },
  // 查询秒杀商品
  querySecKillGoods: function (storeId, productArray) {
    const that = this
    let postData = {
      page: 1,
      pageSize: 0,
      stateIn: 'STARTED',
      storeIdEquals: storeId
    }
    secKillService.query(postData).then(res => {
      productArray.forEach((ele, index) => {
        const productId = ele.productId
        for (let i = 0; i < res.records.length; i++) {
          let data = new Date()
          let nowTimeStamp = new Date(util.formatTime(data)).getTime()
          let newStartTime = new Date(res.records[i].startTime.replace(/-/g, '/')).getTime()
          let newEndTime = new Date(res.records[i].endTime.replace(/-/g, '/')).getTime()
          if (nowTimeStamp >= newStartTime && nowTimeStamp <= newEndTime) {
            for (let j = 0; j < res.records[i].products.length; j++) {
              const item = res.records[i].products[j];
              if (ele.grabActivityId && item.productId == productId) {
                let timeData = {
                  ...ele,
                  sellPrice: item.price,
                  activityId: item.activityId,
                  balance: item.availableStockAmount,
                  secKillInfo: {
                    ...item
                  },
                  checked: item.availableStockAmount === 0 ? false : ele.checked
                }
                productArray[index] = timeData
              }
            }
          }
        }
      })
      console.log("查询秒杀")
      that.setData({
        goodsList: productArray
      })
      that.handlePriceCalc()
      util.setHideLoading(false);
    }).catch(e => {
      console.log(e.message)
    })
  },
  // 购物车删除事件
  handleDelete: function () {
    var self = this;
    let shoppingItems = "";
    this.data.goodsList.forEach(item => {
      if (item.checked) {
        if (shoppingItems === "") {
          shoppingItems = shoppingItems + item.id;
        } else {
          shoppingItems = shoppingItems + "," + item.id;
        }
      }
    })
    if (shoppingItems === "") {
      wx.showToast({
        title: "请选择要删除的商品",
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '确认要删除选中商品？',
        success: function (res) {
          if (res.confirm) {
            shopcartService.remove(shoppingItems).then(res => {
              self.queryShopcart();
              self.queryShopCartNum();
            })
          } else if (res.cancel) {}
        }
      })
    }
  },

  clickDelete: function (val) {
    var that = this;
    let shoppingItems = "";
    if (shoppingItems === '') {
      shoppingItems = shoppingItems + val.currentTarget.dataset.id
    }
    console.log(shoppingItems)
    wx.showModal({
      title: '提示',
      content: '确认要删除该商品？',
      success: function (res) {
        if (res.confirm) {
          shopcartService.remove(shoppingItems).then(res => {
            that.queryShopcart();
            that.queryShopCartNum();
          })
        } else if (res.cancel) {}
      }
    })
  },
  // 去完善订单
  toPerfectOrder: function () {
    const that = this
    let tempGoodsList = [];
    let inventoryDeficiency = [];
    let availableGoodsList = []
    this.data.goodsList.forEach(item => {
      if (item.checked && item.status !== "DELETED") {
        tempGoodsList.push(item)
      }
    })
    console.log(tempGoodsList)
    let canBuyGoodsList = [];
    tempGoodsList.forEach(item => {
      if (item.balance < item.productNum) {
        inventoryDeficiency.push(item)
      } else {
        if (item.secKillInfo) {
          if (item.productNum <= item.secKillInfo.limitCount) {
            availableGoodsList.push(item)
          } else {
            inventoryDeficiency.push(item)
          }
        } else {
          availableGoodsList.push(item)
        }
      }
    });
    var secKillList = []
    availableGoodsList.forEach(item => {
      if (item.activityId !== '' && item.activityId) {
        secKillList.push(item)
      }
    })
    if (tempGoodsList.length > 0) {
      try {
        var shopcart = {
          allPrice: parseFloat(this.data.allPrice),
          goodsList: availableGoodsList,
          orderType: 'normal',
          storeId: app.globalData.storeInfo.id,
          discount: parseFloat(this.data.discount),
          scource: 'SHOPPINGCART'
        }
        if (that.data.tabSelected == 1) {
          shopcart = {
            ...shopcart,
            orderType: 'distribution',
            storeId: that.data.distributionStoreId
          }
        } else {
          console.log(secKillList)
          if (secKillList.length > 0) {
            shopcart = {
              ...shopcart,
              storeId: app.globalData.storeInfo.id,
              orderType: 'secondkill',
            }
          }
        }
        console.log(shopcart)
        wx.setStorageSync('wj_shopcart', shopcart)
      } catch (e) {
        console.log(e.message)
      }
      if (inventoryDeficiency.length > 0) {
        let tips = ''
        inventoryDeficiency.forEach(item => {
          tips = tips + item.name + '、'
        });
        tips = tips.substring(0, tips.length - 1)
        tips = tips + '等' + inventoryDeficiency.length + '件商品库存不足，请选购其他商品哦~'
        console.log(tips)
        wx.showToast({
          title: tips,
          icon: 'none',
          duration: 2000
        })
      } else {
        if (this.data.allPrice > 0) {
          wx.navigateTo({
            url: '../../order/perfectOrder/perfectOrder'
          })
        }
        // 检查手机号
        // if (that.data.hasUserInfo) {
        // } else {
        //   wx.showToast({
        //     title: '您还不是会员，请绑定手机号成为会员',
        //     icon: 'none',
        //     duration: 2000
        //   })
        //   wx.navigateTo({
        //     url: '../bindMobile/bindMobile'
        //   })
        // }
      }
    } else {
      wx.showToast({
        title: '请选择商品',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 检查手机号
  // checkMobile: function() {
  //   const self = this
  //   wx.getStorage({
  //     key: 'wj_member',
  //     success: function(res) {
  //       self.setData({
  //         hasUserInfo: true
  //       })
  //     },
  //     fail: function(error) {
  //       if (error) {
  //         self.setData({
  //           hasUserInfo: false
  //         })
  //       }
  //     }
  //   })
  // },
  // 检查当前用户是否登录授权
  checkAuth: function (e) {
    var self = this;
    if (!app.globalData.userInfo) {
      return false;
    } else {
      return true;
    }
  },
  // 点击切换门店
  changeStore: function () {
    wx.navigateTo({
      url: '../../index/selectStore/selectStore?form=shopCart'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.editTabbar();
    const self = this
    // 查询统配门店信息
    storeService.getDistributionStore().then(res => {
      console.log(res)
      if (res) {
        var distributionStore = res;
        this.setData({
          distributionStoreId: res.id,
          distributionStoreName: res.name
        })
        try {
          wx.setStorageSync('wj_distributionStore', distributionStore)
        } catch (e) {
          console.log(e)
        }
      }
    }).catch(e => {

    })
    if (self.options.mobile && self.options.mobile != '' && self.options.mobile != undefined) {
      const mobile = self.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this
    if (app.globalData.storeInfo) {
      const distributionStoreName = that.data.distributionStoreName
      if (that.data.tabSelected == 0) {
        that.setData({
          storeName: app.globalData.storeInfo.name
        })
      } else {
        that.setData({
          storeName: distributionStoreName
        })
      }
    }
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.member) {
        // that.queryShopCartNum()
        that.queryShopcart();
        // that.checkMobile()
      } else {
        wx.showToast({
          title: '绑定手机号成为会员查看购物袋~',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      wx.showToast({
        title: '请登陆后查看购物袋~',
        icon: 'none',
        duration: 2000
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/goods/shopcart/shopcart?mobile=' + memberId,
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/goods/shopcart/shopcart',
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    }
  },
  recorderPopup: function () {
    this.toggleBottomPopup()
  },
  /**
   * 打开分享弹窗
   */
  toggleBottomPopup() {
    this.toggle('middle');
  },
  toggle(type) {
    this.setData({
      [`show.${type}`]: !this.data.show[type],
      [`overlayStyle`]: this.data.overlayStyle
    });
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handleTabbar: function (e) {
    console.log(e.detail)
    if (e.detail.showTabbar === true) {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    } else {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})